public class DeadLock2 {
    public static String r1="r1";
    public static String r2="r2";

    //主线程启动线程
    public static void main(String[] args) {
        MyRunnable1 myRunnable1 = new MyRunnable1();
        MyRunnable2 myRunnable2 = new MyRunnable2();
        new Thread(myRunnable1).start();
        new Thread(myRunnable2).start();
    }
}

class MyRunnable1 implements Runnable{

    @Override
    public void run() {
        try{
            if (DeadLock2.r1.hashCode() > DeadLock2.r2.hashCode()){
                synchronized(DeadLock2.r1){
                    System.out.println("R1线程锁住了r1");
                    Thread.sleep(3000);
                    synchronized (DeadLock2.r2){
                        System.out.println("R1线程锁住了r2");
                        Thread.sleep(3000);
                    }
                    System.out.println("解锁");
                }
            }else{
                synchronized (DeadLock2.r2){
                    System.out.println("R1线程锁住了r2");
                    Thread.sleep(3000);
                    synchronized (DeadLock2.r1){
                        System.out.println("R1线程锁住了r1");
                        Thread.sleep(3000);
                    }
                    System.out.println("解锁");
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

class MyRunnable2 implements Runnable{

    @Override
    public void run() {
        try {
            if (DeadLock2.r1.hashCode() < DeadLock2.r2.hashCode()){
                synchronized (DeadLock2.r2){
                    System.out.println("R2线程锁住了r2");
                    Thread.sleep(3000);
                    synchronized (DeadLock2.r1){
                        System.out.println("R2线程锁住了r1");
                        Thread.sleep(3000);
                    }
                    System.out.println("解锁");
                }
            }else {
                synchronized (DeadLock2.r1){
                    System.out.println("R2线程锁住了r1");
                    Thread.sleep(3000);
                    synchronized(DeadLock2.r2){
                        System.out.println("R2线程锁住了r2");
                        Thread.sleep(3000);
                    }
                    System.out.println("解锁");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
